﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;
using System.Configuration;

namespace MvcWeb.Filters
{
    public class ApiSecurityFilter : ActionFilterAttribute
    {
        ILog logWriter = LogManager.GetLogger("ApiSecurityFilter");

        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            try
            {
                ResultMsg resultMsg = null;
                var request = actionContext.Request;
                string remethod = request.Method.Method;
                string appSecret = ConfigurationManager.AppSettings["AppSecret"].ToString();

                IDictionary<string, string> parameters = GetDictionaryString(request.RequestUri.Query);
                bool result = SignExtension.Validate(parameters, appSecret, "md5");
                logWriter.Info("result:" + result);
                if (!result)
                {
                    resultMsg = new ResultMsg();
                    resultMsg.returnCode = ((int)StatusCodeEnum.HttpRequestError).ToString();
                    resultMsg.message = StatusCodeEnum.HttpRequestError.GetEnumText();
                    resultMsg.data = "";
                    actionContext.Response = HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg));
                    base.OnActionExecuting(actionContext);
                    logWriter.Info("result:" + result+1);
                    return;
                }
                else
                {
                    base.OnActionExecuting(actionContext);
                    logWriter.Info("result:" + result + 2);
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("OnActionExecuting方法：" + ex.Message);
            }
        }

        /// <summary>
        /// 将查询字符串解析转换为IDictionary<string, string>对象.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public IDictionary<string, string> GetDictionaryString(string queryString)
        {
            queryString = queryString.Replace("?", "");
            logWriter.Info("开始请求GetDictionaryString方法：" + queryString);
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(queryString))
            {
                string[] qcString = queryString.Split('&');
                foreach (string item in qcString)
                {
                    parameters.Add(item.Substring(0, item.IndexOf('=')), HttpUtility.UrlDecode(item.Substring(item.IndexOf('=') + 1)));
                }
            }
            else
            {
                parameters = null;
            }
            return parameters;
        }
    }
}